'use client'

import React, { useState, useRef, useEffect, useCallback } from 'react'
import { Search, MapPin, X, Loader2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card } from '@/components/ui/card'
import { toast } from 'sonner'
import { createPortal } from 'react-dom'

interface SearchResult {
  id: string
  name: string
  address: string
  location: [number, number] // [lng, lat]
  district?: string
  city?: string
  province?: string
  adcode?: string
}

interface AddressSearchInputProps {
  /** 高德地图API密钥 */
  amapKey: string
  /** 搜索结果回调 */
  onLocationSelect: (location: [number, number], address: string, result: SearchResult) => void
  /** 占位符文本 */
  placeholder?: string
  /** 自定义样式类名 */
  className?: string
  /** 搜索城市限制 */
  city?: string
  /** 是否显示当前位置按钮 */
  showCurrentLocation?: boolean
}

export const AddressSearchInput: React.FC<AddressSearchInputProps> = ({
  amapKey,
  onLocationSelect,
  placeholder = "请输入地址进行搜索...",
  className = "",
  city = "全国",
  showCurrentLocation = true
}) => {
  const [searchText, setSearchText] = useState('')
  const [searchResults, setSearchResults] = useState<SearchResult[]>([])
  const [isSearching, setIsSearching] = useState(false)
  const [showResults, setShowResults] = useState(false)
  const [isGettingLocation, setIsGettingLocation] = useState(false)
  const [dropdownPosition, setDropdownPosition] = useState({ top: 0, left: 0, width: 0 })
  
  const searchTimeoutRef = useRef<NodeJS.Timeout>()
  const amapRef = useRef<any>(null)
  const geocoderRef = useRef<any>(null)
  const inputContainerRef = useRef<HTMLDivElement>(null)

  // 初始化高德地图API
  useEffect(() => {
    const initAMap = async () => {
      try {
        if (!window.AMap) {
          const AMapLoader = (await import('@amap/amap-jsapi-loader')).default
          await AMapLoader.load({
            key: amapKey,
            version: '2.0',
            plugins: ['AMap.Geocoder', 'AMap.PlaceSearch', 'AMap.Geolocation']
          })
        }
        
        amapRef.current = window.AMap
        
        // 检查Geocoder是否可用
        if (window.AMap && window.AMap.Geocoder) {
          try {
            geocoderRef.current = new window.AMap.Geocoder({
              city: city === '全国' ? undefined : city
            })
            console.log('Geocoder初始化成功')
          } catch (geocoderError) {
            console.warn('Geocoder初始化失败，将仅使用Web API:', geocoderError)
            geocoderRef.current = null
          }
        } else {
          console.warn('Geocoder插件未加载，将仅使用Web API')
          geocoderRef.current = null
        }
      } catch (error) {
        console.error('高德地图API加载失败:', error)
        toast.error('地图服务初始化失败')
      }
    }

    initAMap()
  }, [amapKey, city])

  // 更新下拉框位置
  const updateDropdownPosition = useCallback(() => {
    if (inputContainerRef.current) {
      const rect = inputContainerRef.current.getBoundingClientRect()
      setDropdownPosition({
        top: rect.bottom + window.scrollY + 4,
        left: rect.left + window.scrollX,
        width: rect.width
      })
    }
  }, [])

  // 地址搜索 - 优先搜索POI（医院等兴趣点）
  const searchAddress = useCallback(async (query: string): Promise<SearchResult[]> => {
    if (!query.trim()) return []

    setIsSearching(true)
    
    try {
      // 优先使用高德POI搜索
      const poiResults = await searchPOI(query, city === '全国' ? undefined : city)
      if (poiResults.length > 0) {
        return poiResults
      }

      // 如果POI搜索无结果，则使用Web API搜索
      return await searchWithWebAPI(query, city === '全国' ? undefined : city)
      
    } catch (error) {
      console.error('地址搜索失败:', error)
      return []
    } finally {
      setIsSearching(false)
    }
  }, [city])

  // 使用高德POI搜索
  const searchPOI = useCallback(async (query: string, searchCity?: string): Promise<SearchResult[]> => {
    if (!amapRef.current || !window.AMap) return []

    return new Promise((resolve) => {
      try {
        const placeSearch = new window.AMap.PlaceSearch({
          city: searchCity,
          citylimit: searchCity ? true : false,
          pageSize: 10,
          pageIndex: 1,
          type: '医疗保健服务|生活服务|政府机构及社会团体' // 优先搜索医院等POI
        })

        placeSearch.search(query, (status: string, result: any) => {
          if (status === 'complete' && result.poiList) {
            const pois = result.poiList.pois || []
            const searchResults: SearchResult[] = pois.map((poi: any, index: number) => ({
              id: poi.id || `poi-${index}`,
              name: poi.name,
              address: poi.address || poi.pname + poi.cityname + poi.adname,
              location: [poi.location.lng, poi.location.lat],
              district: poi.adname,
              city: poi.cityname,
              province: poi.pname,
              adcode: poi.adcode
            }))
            
            console.log('POI搜索结果:', searchResults)
            resolve(searchResults)
          } else {
            console.log('POI搜索无结果:', status, result)
            resolve([])
          }
        })
      } catch (error) {
        console.error('POI搜索错误:', error)
        resolve([])
      }
    })
  }, [amapRef])

  // 使用Web API搜索
  const searchWithWebAPI = useCallback(async (query: string, searchCity?: string): Promise<SearchResult[]> => {
    try {
      const cityParam = searchCity && searchCity !== '全国' ? `&city=${encodeURIComponent(searchCity)}` : ''
      const url = `https://restapi.amap.com/v3/place/text?key=${amapKey}&keywords=${encodeURIComponent(query)}&types=医疗保健服务|生活服务${cityParam}&output=json&offset=10&page=1`
      
      const response = await fetch(url)
      const data = await response.json()
      
      if (data.status === '1' && data.pois) {
        const results: SearchResult[] = data.pois.map((poi: any, index: number) => {
          const location = poi.location.split(',').map(Number)
          return {
            id: poi.id || `web-poi-${index}`,
            name: poi.name,
            address: poi.address,
            location: [location[0], location[1]],
            district: poi.adname,
            city: poi.cityname,
            province: poi.pname,
            adcode: poi.adcode
          }
        })
        
        console.log('Web API搜索结果:', results)
        return results
      }
      
      console.log('Web API搜索无结果:', data)
      return []
    } catch (error) {
      console.error('Web API搜索错误:', error)
      return []
    }
  }, [amapKey])

  // 处理输入变化
  const handleInputChange = (value: string) => {
    setSearchText(value)
    
    // 清除之前的搜索定时器
    if (searchTimeoutRef.current) {
      clearTimeout(searchTimeoutRef.current)
    }

    if (value.trim()) {
      // 延迟搜索，避免频繁请求
      searchTimeoutRef.current = setTimeout(async () => {
        const results = await searchAddress(value)
        setSearchResults(results || [])
        setShowResults(true)
        updateDropdownPosition()
      }, 500)
    } else {
      setSearchResults([])
      setShowResults(true) // 显示搜索建议
      updateDropdownPosition()
    }
  }

  // 处理输入框焦点
  const handleInputFocus = () => {
    updateDropdownPosition()
    if (!searchText.trim()) {
      setShowResults(true) // 显示搜索建议
    }
  }

  // 选择搜索结果
  const handleResultSelect = (result: SearchResult) => {
    setSearchText(result.name)
    setShowResults(false)
    onLocationSelect(result.location, result.address, result)
    toast.success(`已定位到：${result.name}`)
  }

  // 获取当前位置
  const getCurrentLocation = () => {
    if (!navigator.geolocation) {
      toast.error('浏览器不支持定位功能')
      return
    }

    setIsGettingLocation(true)
    
    navigator.geolocation.getCurrentPosition(
      async (position) => {
        const { longitude, latitude } = position.coords
        
        try {
          // 使用逆地理编码获取地址信息
          if (geocoderRef.current) {
            geocoderRef.current.getAddress([longitude, latitude], (status: string, result: any) => {
              if (status === 'complete' && result.regeocode) {
                const address = result.regeocode.formattedAddress
                const currentLocation: SearchResult = {
                  id: 'current-location',
                  name: '当前位置',
                  address: address,
                  location: [longitude, latitude],
                  district: result.regeocode.addressComponent?.district,
                  city: result.regeocode.addressComponent?.city,
                  province: result.regeocode.addressComponent?.province
                }
                
                setSearchText('当前位置')
                setShowResults(false)
                onLocationSelect([longitude, latitude], address, currentLocation)
                toast.success('已定位到当前位置')
              } else {
                // 逆地理编码失败，使用基本位置信息
                const currentLocation: SearchResult = {
                  id: 'current-location',
                  name: '当前位置',
                  address: `经度: ${longitude.toFixed(6)}, 纬度: ${latitude.toFixed(6)}`,
                  location: [longitude, latitude]
                }
                
                setSearchText('当前位置')
                setShowResults(false)
                onLocationSelect([longitude, latitude], currentLocation.address, currentLocation)
                toast.success('已定位到当前位置')
              }
            })
          } else {
            // 没有Geocoder，直接使用坐标
            const currentLocation: SearchResult = {
              id: 'current-location',
              name: '当前位置',
              address: `经度: ${longitude.toFixed(6)}, 纬度: ${latitude.toFixed(6)}`,
              location: [longitude, latitude]
            }
            
            setSearchText('当前位置')
            setShowResults(false)
            onLocationSelect([longitude, latitude], currentLocation.address, currentLocation)
            toast.success('已定位到当前位置')
          }
        } catch (error) {
          console.error('逆地理编码失败:', error)
          toast.error('获取地址信息失败')
        } finally {
          setIsGettingLocation(false)
        }
      },
      (error) => {
        console.error('定位失败:', error)
        setIsGettingLocation(false)
        
        switch (error.code) {
          case error.PERMISSION_DENIED:
            toast.error('定位权限被拒绝，请在浏览器设置中允许定位')
            break
          case error.POSITION_UNAVAILABLE:
            toast.error('定位信息不可用')
            break
          case error.TIMEOUT:
            toast.error('定位请求超时')
            break
          default:
            toast.error('获取位置失败')
            break
        }
      },
      {
        enableHighAccuracy: true,
        timeout: 15000,
        maximumAge: 300000
      }
    )
  }

  // 点击外部关闭下拉框
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (inputContainerRef.current && !inputContainerRef.current.contains(event.target as Node)) {
        setShowResults(false)
      }
    }

    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [])

  // 渲染下拉框内容
  const renderDropdown = () => {
    if (!showResults) return null

    const dropdownContent = (
      <div
        className="fixed bg-white border border-gray-200 rounded-lg shadow-lg max-h-80 overflow-y-auto"
        style={{
          top: `${dropdownPosition.top}px`,
          left: `${dropdownPosition.left}px`,
          width: `${dropdownPosition.width}px`,
          zIndex: 99999
        }}
      >
        {/* 搜索结果列表 */}
        {searchResults.length > 0 && (
          <div className="p-2">
            {searchResults.map((result) => (
              <div
                key={result.id}
                onClick={() => handleResultSelect(result)}
                className="flex items-start gap-3 p-3 hover:bg-gray-50 cursor-pointer rounded-lg transition-colors"
              >
                <MapPin className="w-4 h-4 text-blue-500 mt-1 flex-shrink-0" />
                <div className="flex-1 min-w-0">
                  <div className="font-medium text-gray-900 truncate">
                    {result.name}
                  </div>
                  <div className="text-sm text-gray-500 truncate">
                    {result.address}
                  </div>
                  {result.district && result.city && (
                    <div className="text-xs text-gray-400 mt-1">
                      {result.province} {result.city} {result.district}
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}

        {/* 无搜索结果提示 */}
        {searchResults.length === 0 && searchText.trim() && !isSearching && (
          <div className="p-4 text-center text-gray-500">
            <MapPin className="w-8 h-8 mx-auto mb-2 text-gray-300" />
            <div>未找到相关地址</div>
            <div className="text-sm mt-1">请尝试更换关键词</div>
          </div>
        )}

        {/* 搜索建议（当输入框为空时显示） */}
        {searchText.trim() === '' && (
          <div className="p-3">
            <div className="text-sm font-medium text-gray-700 mb-2">搜索建议</div>
            {[
              '保定市第一医院',
              '保定市人民医院',
              '保定市第二医院',
              '保定市第三医院',
              '保定市儿童医院',
              '保定市中医院',
              '保定市妇幼保健院',
              '河北大学附属医院',
              '北京协和医院',
              '上海瑞金医院'
            ].map((suggestion, index) => (
              <div
                key={index}
                onClick={() => handleInputChange(suggestion)}
                className="flex items-center gap-2 p-2 hover:bg-gray-50 cursor-pointer rounded text-sm text-gray-600"
              >
                <MapPin className="w-3 h-3 text-gray-400" />
                {suggestion}
              </div>
            ))}
          </div>
        )}
      </div>
    )

    // 使用 Portal 将下拉框渲染到 body
    return typeof window !== 'undefined' ? createPortal(dropdownContent, document.body) : null
  }

  return (
    <div className={`relative address-search-container ${className}`} ref={inputContainerRef}>
      {/* 搜索输入框 */}
      <div className="relative">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
          <Input
            type="text"
            value={searchText}
            onChange={(e) => handleInputChange(e.target.value)}
            onFocus={handleInputFocus}
            placeholder={placeholder}
            className="pl-10 pr-20 bg-white/80 backdrop-blur-sm border-white/20 text-gray-900 placeholder:text-gray-500"
            disabled={isSearching}
          />
          <div className="absolute right-2 top-1/2 transform -translate-y-1/2 flex items-center gap-1">
            {searchText && (
              <Button
                type="button"
                variant="ghost"
                size="sm"
                onClick={() => {
                  setSearchText('')
                  setSearchResults([])
                  setShowResults(false)
                }}
                className="h-6 w-6 p-0 hover:bg-gray-200/50"
              >
                <X className="w-3 h-3" />
              </Button>
            )}
            
            {showCurrentLocation && (
              <Button
                type="button"
                variant="ghost"
                size="sm"
                onClick={getCurrentLocation}
                disabled={isGettingLocation}
                className="h-6 w-6 p-0 hover:bg-blue-100 text-blue-600"
                title="获取当前位置"
              >
                {isGettingLocation ? (
                  <Loader2 className="w-3 h-3 animate-spin" />
                ) : (
                  <MapPin className="w-3 h-3" />
                )}
              </Button>
            )}
          </div>
        </div>

        {/* 搜索中状态 */}
        {isSearching && (
          <div className="absolute left-3 top-1/2 transform -translate-y-1/2">
            <Loader2 className="w-4 h-4 animate-spin text-blue-500" />
          </div>
        )}
      </div>

      {/* 使用Portal渲染下拉框 */}
      {renderDropdown()}
    </div>
  )
}

export default AddressSearchInput